/* eslint-disable default-case */
/* eslint-disable no-unused-expressions */
// fetch封装
import qs from "qs"
let baseURL = "http://localhost:3000"

export default function request(url, options = {}) {
  url = baseURL + url
    /**
     * GET系列请求的封装
     */
    // eslint-disable-next-line no-unused-expressions
    !options.method ? options.method = 'GET' : null
  if (options.hasOwnProperty('params')) {
    if (/^(GET|DELETE|HEAD|OPTIONS)$/i.test(options.method)) {
      const ask = url.includes('?') ? '&' : "?"
      url += `${ask}${qs.stringify(options.params)}`
    }
    delete options.params
  }

  /**
   * 合并配置项
   */
  options = Object.assign({
    // 允许跨越携带资源凭证 same-origin同源可以omit都拒绝
    credentials: 'include',
    // 设置请求头
    headers: {}
  }, options)
  options.headers.Accept = 'application/json'

  /**
   * token的校验
   */

  const token = localStorage.getItem('token')
  token && (options.headers.Authorization = token)

  /**
   * post球球处理
   */
  if (/^(POST|PUT)$/i.test(options.method)) {
    !options.type ? options.type = 'urlencoded' : null
    if (options.type === 'urlencoded') {
      options.headers['Content-type'] = 'application/x-www-form-urlencoded'
      options.body = qs.stringify(options.params)
    }
    if (options.type === 'json') {
      options.headers['Content-type'] = 'application/json'
      options.body = qs.stringify(options.params)
    }
  }

  return fetch(url, options).then(response => {
    if (!/^(2|3)\d{2}$/.test(response.status)) {
      switch (response.status) {
        case 401:
          break
      }
      return Promise.reject(response)
    }
  }).catch(error => {
    if (!window.navigator.onLine) {
      // 断开网络了，可以让其跳转到断网页面
      return
    }
    return Promise.reject(error)
  })

}